/*
* $Id: ChangeFamilyOperation.cpp 336 2011-09-28 06:06:36Z volok-aleksej@yandex.ru $
*
* Copyright 2009-2011 by Volokitin Aleksey
* All rights reserved
*
*/
#include "Common/include.h"
#include "ChangeFamilyOperation.h"
#include "Database/TransactManager.h"
#include "Database/Tables/FamiliesTable.h"
#include "Database/Tables/FieldValuesTable.h"

CChangeFamilyOperation::CChangeFamilyOperation(CTransactManager* pManager)
: m_pManager(pManager){}
CChangeFamilyOperation::~CChangeFamilyOperation(){}

std::tstring CChangeFamilyOperation::ExecuteOperation(IDatabase* pDatabase, IReader* pReader){
	CFamiliesTable families;
	CFieldValuesTable fieldValue;
	int size;
	pReader->ReadInt(size);
	int lenData = 0;
	int idFamily;
	lenData = pReader->ReadInt(idFamily);
	families.m_content.s_nId = m_pManager->GetRealId(
		CTransactManager::ID(CTransactManager::FAMILY, idFamily));
	lenData += pReader->ReadUTF(families.m_content.s_strName);
	std::tstring strNameFamily = families.m_content.s_strName;
	int idPoint;
	lenData += pReader->ReadInt(idPoint);
	families.m_content.s_nIdPoint = m_pManager->GetRealId(
		CTransactManager::ID(CTransactManager::POINT, idPoint));
	lenData += pReader->ReadInt((int&)families.m_content.s_type);
	lenData += pReader->ReadUTF(families.m_content.s_strNote);
	int idRecord;
	lenData += (Family::type)pReader->ReadInt(idRecord);
	if(idRecord != 0)
		families.m_content.s_nIdRecord = m_pManager->GetRealId(
			CTransactManager::ID(CTransactManager::FIELD_VALUE, idRecord));
	families.UpdateValue(pDatabase);
	while (lenData < size){
		bool bExist = false;
		lenData += pReader->ReadInt(idRecord);
		idRecord = m_pManager->GetRealId(
			CTransactManager::ID(CTransactManager::FIELD_VALUE, idRecord));
		fieldValue.m_content.s_nId = idRecord;
		IResult* pResult = fieldValue.GetValue(pDatabase);
		if(pResult->GetSizeResult())
			bExist = true;
		pResult->Free();
		fieldValue.m_content.s_nId = idRecord;
		lenData += pReader->ReadUTF(fieldValue.m_content.s_strName);
		lenData += pReader->ReadUTF(fieldValue.m_content.s_strValue);
		lenData += pReader->ReadInt((int&)fieldValue.m_content.s_type);
		if(bExist)
			fieldValue.UpdateValue(pDatabase);
		else
			fieldValue.SetValue(pDatabase);
	}
	std::tstring strLog = ILanguageManager::GetLanguageManager()->GetString(CHANGE_FAMILY_LOG_ID);
	return strLog + _T(" ") + strNameFamily;
}

void CChangeFamilyOperation::Free(){
	delete this;
}
